<?php

/**
 * 护理评估模块模型
 * @authors Hex (hex@zpdchina.com)
 * @date    2017-03-06 15:26:18
 * @version $Id$
 */
class HuliPingguModel extends BaseModel
{
    //保存护理评估相关数据
    public function saveData($upload_data, $yiyuan_id)
    {
        $totalPingfen = 0;
        try {
            $db = Database::instance();
            $db->begin();// 开启一个事务
            //保存评估护理单项目数据
            foreach ($upload_data as &$val) {
                $biaodan_id = $val['biaodan_id'];
                $arr['biaodan_name'] = $val['biaodan_name'];
                $arr['hulipinggu_id'] = $hulipinggu_id = $val['hulipinggu_id'];
                $arr['xiangmu_id'] = $val['xiangmu_zuhao'];
                $arr['xiangmu_name'] = $val['xiangmu_name'];
                $arr['xiangmu_xuanxiang'] = $val['xiangmu_leibie'];
                $arr['xiangmu_fenzhi'] = $val['xiangmu_fenzhi'];
                $arr['zhuyuan_id'] = $zhuyuan_id = $val['zhuyuan_id'];
                $arr['hushi_id'] = $hushi_id = $val['hushi_id'];
                $arr['hushi_name'] = $hushi_name = $val['hushi_name'];
                $arr['jilu_shijian'] = $jilu_shijian = $val['jilu_shijian'];
                $arr['yiyuan_id'] = $yiyuan_id;
                $tmp_arr[] = $arr;
                $totalPingfen += $val['xiangmu_fenzhi'];
            }
            unset($val);
            $row = Utility::multiInsert('yuanwai_huli_pinggu', $tmp_arr);
            if (!$row) throw new Exception('项目数据保存失败');
            //根据表单编号、总评分获取对应的评分评估配置表
            $pingfen_info = DB::select('*')
                ->from('data_hulipinggu_pingfen')
                ->where('biaodan_id', '=', $biaodan_id)
                ->and_where('yiyuan_id', '=', $yiyuan_id)
                ->and_where('pinggu_defen_min', '<=', $totalPingfen)
                ->and_where_open()
                ->where('pinggu_defen_max', '>=', $totalPingfen)
                ->or_where('pinggu_defen_max', '=', '')
                ->and_where_close()
                ->order_by('pinggu_defen_min', 'DESC')
                ->execute()
                ->current();
            //保存护理单数据
            $days = $pingfen_info['huli_zhouqi_content'] ?: 0;
            $newdays = $days ? ($days - 1) : 0;
            $hulidan['id'] = $hulipinggu_id;
            $hulidan['zhuyuan_id'] = $zhuyuan_id;
            $hulidan['biaodan_id'] = $biaodan_id;
            $hulidan['pingfen_id'] = $pingfen_info['id'];
            $hulidan['pinggu_defen'] = $totalPingfen;
            $hulidan['huli_zhouqi'] = $days;
            $hulidan['hushi_name'] = $hushi_name;
            $hulidan['hushi_id'] = $hushi_id;
            $hulidan['create_time'] = $hulidan['update_time'] = $jilu_shijian;
            $hulidan['start_time'] = date('Y-m-d 00:00:00', time());
            $hulidan['finish_time'] = date('Y-m-d 23:59:59', strtotime("+$newdays day"));
            $hulidan['yiyuan_id'] = $yiyuan_id;
            $row2 = CommonModel::addData('yuanwai_huli_pinggu_hulidan',$hulidan);
            if (!$row2) throw new Exception('评估护理单数据保存失败');
            //根据评估配置表id获取评估单措施明细 护理周期不为0 插入护理措施
            if (Yaconf::get("config$yiyuan_id.is_hulipinggu_cuoshi") && $days > 0) {
                //获取评分表对应的护理措施数据
                $cuoshi_info = $this->getHuliCuoshi($pingfen_info['id'], $yiyuan_id);
                if ($cuoshi_info) {
                    for ($i = 0; $i < $days; $i++) {
                        foreach ($cuoshi_info as $v) {
                            $data['zhuyuan_id'] = $zhuyuan_id;
                            $data['hulipinggu_id'] = $hulipinggu_id;
                            $data['cuoshi_id'] = $v['id'];
                            $data['cuoshi_content'] = $v['content'];
                            $data['create_time'] = $jilutime = $jilu_shijian . date(":s");
                            $data['zhixing_time'] = date('Y-m-d H:i:s', strtotime("$jilutime +$i day"));
                            $data['zhixinged_time'] = $data['zhixing_hushi_id'] = $data['zhixing_hushi_name'] = $data['beizhu'] = '';
                            $data['is_zhixing'] = 0;
                            $data['yiyuan_id'] = $yiyuan_id;
                            $new_cuoshi_data[] = $data;
                        }
                    }
                    $row3 = Utility::multiInsert('yuanwai_huli_pinggu_cuoshi_zhixing', $new_cuoshi_data);
                    if (!$row3) throw new Exception('护理措施保存失败');
                }
            }
            $db->commit();//成功则提交
//            Utility::apiJsonResult('', '保存成功');
            $result['staus'] = '1';
            $result['result'] = "保存成功";
        } catch (Exception $e) {
            $db->rollback();//不成功，则回滚
//            Utility::apiJsonError(30005, '保存失败');
            $result['staus'] = '0';
            $result['result'] = "保存失败";
        }
        return $result;
    }

    /**
     * 获取患者最新一条护理评估单
     * @param  string $biaodan_id [表单编号]
     * @param  string $zhuyuan_id [住院编号]
     * @param  string $yiyuan_id [医院编号]
     * @return
     */
    public function getHulidanInfo($biaodan_id = '', $zhuyuan_id = '', $yiyuan_id)
    {
        $data = DB::select('id,pingfen_id,huli_zhouqi,start_time,finish_time')
            ->from('yuanwai_huli_pinggu_hulidan')
            ->where('yiyuan_id', '=', $yiyuan_id)
            ->and_where('biaodan_id', '=', $biaodan_id)
            ->and_where('zhuyuan_id', '=', $zhuyuan_id)
            ->order_by('id', 'DESC')
            ->execute()
            ->current();
        return $data;
    }


    /**
     * 护理评估单是否存在护理周期内未执行的护理措施
     * @param  string $id [评估单编号]
     * @param  string $finish_time [护理周期结束时间]
     * @param  string $yiyuan_id [医院编号]
     * @return
     */
    public function getUnzhixingData($id, $finish_time, $yiyuan_id)
    {
        $data = DB::select('*')
            ->from('yuanwai_huli_pinggu_cuoshi_zhixing')
            ->where('hulipinggu_id', '=', $id)
            ->and_where('yiyuan_id', '=', $yiyuan_id)
            ->and_where('left(zhixing_time,10)', '=', date("Y-m-d", strtotime($finish_time)))
            ->and_where_open()
            ->where('is_zhixing', '=', 0)
            ->or_where('zhixinged_time', 'IS', NULL)
            ->and_where_close()
            ->execute()
            ->as_array();
        return $data;
    }


    /**
     * 获取措施数据
     * @param  string $pingfen_id [评分表编号]
     * @param  string $yiyuan_id [医院编号]
     * @return
     */
    public function getHuliCuoshi($pingfen_id, $yiyuan_id)
    {
        return DB::select('c.*')
            ->from(array('data_hulipinggu_cuoshi', 'c'))
            ->join(array('data_hulipinggu_pingfen_cuoshi', 'p'), 'LEFT')
            ->on('c.id', '=', 'p.cuoshi_id')
            ->on('c.yiyuan_id', '=', 'p.yiyuan_id')
            ->where('p.pingfen_id', '=', $pingfen_id)
            ->where('c.yiyuan_id', '=', $yiyuan_id)
            ->execute()
            ->as_array();
    }

    public function updateData($upload_data, $yiyuan_id)
    {
        $zhixing_id_arr = explode(',', $upload_data['zhixing_id']);
        return DB::update('zhuyuan_huli_pinggu_cuoshi_zhixing')
            ->set(array('zhixing_hushi_id' => $upload_data['zhixing_hushi_id'],
                    'zhixing_hushi_name' => $upload_data['zhixing_hushi_name'],
                    'zhixinged_time' => $upload_data['zhixing_time'],
                    'is_zhixing' => 1)
            )
            ->where('id', 'IN', $zhixing_id_arr)
            ->and_where('yiyuan_id', '=', $yiyuan_id)
            ->execute();
    }

    public function getPingguData($zhuyuan_id, $yiyuan_id, $biaodan_id = '', $jilu_shijian = '')
    {
        $query = DB::select("p.*,b.biaodan_name,f.weixian_dengji_content as weixiandengji,'上门' data_type")
            ->from(array('yuanwai_huli_pinggu_hulidan', 'p'))
            ->join(array('data_hulipinggu_biaodan', 'b'), 'LEFT')
            ->on('p.biaodan_id', '=', 'b.id')
            ->on('p.yiyuan_id', '=', 'b.yiyuan_id')
            ->join(array('data_hulipinggu_pingfen', 'f'), 'LEFT')
            ->on('p.pingfen_id', '=', 'f.id')
            ->on('p.yiyuan_id', '=', 'f.yiyuan_id')
            ->where('p.zhuyuan_id', '=', $zhuyuan_id)
            ->where('p.is_rebuild', '=', 0)
            ->where('p.yiyuan_id', '=', $yiyuan_id);
        //判断是否开启评估提醒功能 若开启则返回患者所有评估单 未开启则返回护理周期内的数据
//        if (!Yaconf::get("config$yiyuan_id.is_hulipinggu_remind")) {
//            $jilu_shijian = $jilu_shijian ? $jilu_shijian . date(" H:i:s") : date("Y-m-d H:i:s");
//            $query->where('p.start_time', '<', $jilu_shijian);
//            $query->where('p.finish_time', '>', $jilu_shijian);
//        }

        if ($biaodan_id)
            $query->where('p.biaodan_id', '=', $biaodan_id);
        $pinggu_data = $query->order_by('p.id desc')
            ->execute()
            ->as_array();
        return $pinggu_data;
    }

    public function getPingguDatawainei($zhuyuan_id, $yiyuan_id, $biaodan_id = '', $jilu_shijian = '')
    {
        $query = DB::select("p.*,b.biaodan_name,f.weixian_dengji_content as weixiandengji,'电话' data_type")
            ->from(array('zhuyuan_huli_pinggu_hulidan', 'p'))
            ->join(array('data_hulipinggu_biaodan', 'b'), 'LEFT')
            ->on('p.biaodan_id', '=', 'b.id')
            ->on('p.yiyuan_id', '=', 'b.yiyuan_id')
            ->join(array('data_hulipinggu_pingfen', 'f'), 'LEFT')
            ->on('p.pingfen_id', '=', 'f.id')
            ->on('p.yiyuan_id', '=', 'f.yiyuan_id')
            ->where('p.zhuyuan_id', '=', $zhuyuan_id)
            ->where('p.is_rebuild', '=', 0)
            ->where('p.yiyuan_id', '=', $yiyuan_id);
        //判断是否开启评估提醒功能 若开启则返回患者所有评估单 未开启则返回护理周期内的数据
//        if (!Yaconf::get("config$yiyuan_id.is_hulipinggu_remind")) {
//            $jilu_shijian = $jilu_shijian ? $jilu_shijian . date(" H:i:s") : date("Y-m-d H:i:s");
//            $query->where('p.start_time', '<', $jilu_shijian);
//            $query->where('p.finish_time', '>', $jilu_shijian);
//        }
        if ($biaodan_id)
            $query->where('p.biaodan_id', '=', $biaodan_id);
        $pinggu_data = $query->order_by('p.id desc')
            ->execute()
            ->as_array();
        return $pinggu_data;
    }

    public function getCuoshiZhixing($hulipinggu_id,$data_type,$istime = true, $iszhixing)
    {
        $table = 'yuanwai_huli_pinggu_cuoshi_zhixing';
        if($data_type =="上门")
        {
            $table = 'yuanwai_huli_pinggu_cuoshi_zhixing';
        }else
        {
            $table = 'zhuyuan_huli_pinggu_cuoshi_zhixing';
        }
        $query = DB::select('*')
            ->from($table)
            ->where('hulipinggu_id', '=', $hulipinggu_id)
            ->where('yiyuan_id', '=', $this->yiyuan_id);
        if ($istime)
            $query->where('left(zhixing_time,10)', '=', date("Y-m-d"));
        if(isset($iszhixing))
            $query->where('is_zhixing', '=', $iszhixing);
        $data = $query->execute()->as_array();
        return $data;
    }

    public function getXiangmuData($hulipinggu_id,$data_type="上门")
    {
        if($data_type=="上门")
        {
            return DB::select('*')
                ->from('yuanwai_huli_pinggu')
                ->where('hulipinggu_id', '=', $hulipinggu_id)
                ->where('yiyuan_id', '=', $this->yiyuan_id)
                ->execute()
                ->as_array();
        }else{
            return DB::select('*')
                ->from('zhuyuan_huli_pinggu')
                ->where('hulipinggu_id', '=', $hulipinggu_id)
                ->where('yiyuan_id', '=', $this->yiyuan_id)
                ->execute()
                ->as_array();
        }

    }

    public function getTongjiNum($zhuyuan_id, $yiyuan_id)
    {
        //判断是否开启评估提醒功能 若开启则返回患者已做过评估的表单类型的已结束的评估单的总数
        //获取表单类型
        $query = DB::select('id')
            ->from('data_hulipinggu_biaodan')
            ->where('yiyuan_id', '=', $yiyuan_id);
        if (Yaconf::get("config$yiyuan_id.hospital_name") == '丰县人民医院') {//丰县人民医院 疼痛评估 不需要提醒
            $query->where('biaodan_name', 'NOT LIKE', '%疼痛%');
        }
        $biaodan_id_arr = array_column($query->execute()->as_array(), 'id');
        $pinggu_count = 0;
        if (!empty($biaodan_id_arr)) {
            foreach ($biaodan_id_arr as $v) {
                //判断该表单类型当天是否评估过 评估过则不提醒
                $today = DB::select('*')
                    ->from('zhuyuan_huli_pinggu_hulidan')
                    ->where('zhuyuan_id', '=', $zhuyuan_id)
                    ->where('biaodan_id', '=', $v)
                    ->where('yiyuan_id', '=', $yiyuan_id)
                    ->where('left(create_time,10)', '=', date("Y-m-d"))
                    ->execute()->current();
                if (empty($today)) {
                    $query = DB::select('*')
                        ->from(array('zhuyuan_huli_pinggu_hulidan', 'p'))
                        ->join(array('data_hulipinggu_pingfen', 'f'), 'LEFT')
                        ->on('p.pingfen_id', '=', 'f.id')
                        ->on('p.yiyuan_id', '=', 'f.yiyuan_id')
                        ->where('p.zhuyuan_id', '=', $zhuyuan_id)
                        ->where('p.biaodan_id', '=', $v)
                        ->where('p.is_rebuild', '=', 0)
                        ->where('p.yiyuan_id', '=', $yiyuan_id);
                    if (Yaconf::get("config$yiyuan_id.hospital_name") == '丰县人民医院') { //丰县人民医院 只提示昨天结束的护理单
                        $query->where('p.finish_time', '=', date('Y-m-d 23:59:59', strtotime("-1 day")));
                    } else {
                        $query->where('p.finish_time', '<', date("Y-m-d H:i:s"));
                    }
                    $info = $query->and_where_open()
                        ->where('f.weixian_dengji_content', 'LIKE', '%中%')
                        ->or_where('f.weixian_dengji_content', 'LIKE', '%高%')
                        ->or_where('f.weixian_dengji_content', 'LIKE', '%重%')
                        ->or_where('f.weixian_dengji_content', 'LIKE', '%非常%')
                        ->and_where_close()
                        ->order_by('p.id desc')
                        ->execute()
                        ->current();
                    if ($info) //获取最新一条数据 符合条件 总数+1
                        $pinggu_count++;
                }
            }
        }
        //获取当天未执行的措施总数 排除护理评估单已删除的数据
        $cuoshi_count = DB::select('COUNT("*") AS total')
            ->from(array('zhuyuan_huli_pinggu_hulidan', 'p'))
            ->join(array('zhuyuan_huli_pinggu_cuoshi_zhixing', 'c'), 'LEFT')
            ->on('p.id', '=', 'c.hulipinggu_id')
            ->on('p.yiyuan_id', '=', 'c.yiyuan_id')
            ->where('c.is_zhixing', '=', 0)
            ->where('left(c.zhixing_time,10)', '=', date("Y-m-d"))
            ->where('p.zhuyuan_id', '=', $zhuyuan_id)
            ->where('p.yiyuan_id', '=', $yiyuan_id)
            ->execute()
            ->get('total',0);
        $count['pinggu_count'] = Yaconf::get("config$yiyuan_id.is_hulipinggu_remind") ? (int)$pinggu_count : 0;
        $count['cuoshi_count'] = Yaconf::get("config$yiyuan_id.is_hulipinggu_remind") ? (int)$cuoshi_count : 0;
        return $count;
    }

}